<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>机器人管理系统</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link href="https://cdn.jsdelivr.net/npm/font-awesome@4.7.0/css/font-awesome.min.css" rel="stylesheet">
    <script src="https://cdn.jsdelivr.net/npm/chart.js@4.4.8/dist/chart.umd.min.js"></script>
    <script>
        // Tailwind 配置
        tailwind.config = {
            theme: {
                extend: {
                    colors: {
                        primary: '#165DFF',
                        secondary: '#36CFC9',
                        success: '#52C41A',
                        warning: '#FAAD14',
                        danger: '#FF4D4F',
                        dark: '#1D2129',
                        'dark-2': '#4E5969',
                        'light-1': '#F2F3F5',
                        'light-2': '#E5E6EB'
                    },
                    fontFamily: {
                        inter: ['Inter', 'system-ui', 'sans-serif'],
                    },
                }
            }
        }
    </script>
    <style type="text/tailwindcss">
        @layer utilities {
            .content-auto {
                content-visibility: auto;
            }
            .scrollbar-hide {
                -ms-overflow-style: none;
                scrollbar-width: none;
            }
            .scrollbar-hide::-webkit-scrollbar {
                display: none;
            }
            .card-shadow {
                box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
            }
            .hover-scale {
                transition: transform 0.2s ease;
            }
            .hover-scale:hover {
                transform: scale(1.02);
            }
            .progress-bar {
                transition: width 0.5s ease;
            }
            .form-input-focus {
                @apply focus:outline-none focus:ring-2 focus:ring-primary/30 focus:border-primary transition-all;
            }
            .modal-enter {
                animation: modalEnter 0.3s ease forwards;
            }
            @keyframes modalEnter {
                from {
                    opacity: 0;
                    transform: translateY(-20px);
                }
                to {
                    opacity: 1;
                    transform: translateY(0);
                }
            }
        }
    </style>
</head>
<body class="font-inter bg-light-1 text-dark overflow-x-hidden">
    <div class="flex h-screen">
        <!-- 侧边栏 -->
        <aside id="sidebar" class="w-64 bg-white h-full card-shadow transition-all duration-300 ease-in-out fixed lg:relative z-20 transform -translate-x-full lg:translate-x-0">
            <div class="p-4 border-b border-light-2 flex items-center justify-between">
                <div class="flex items-center space-x-2">
                    <i class="fa fa-robot text-primary text-2xl"></i>
                    <h1 class="text-xl font-bold text-dark">机器人管理</h1>
                </div>
                <button id="sidebar-toggle" class="lg:hidden text-dark-2">
                    <i class="fa fa-times"></i>
                </button>
            </div>
            
            <nav class="py-4">
                <ul>
                    <li class="mb-1">
                        <a href="#dashboard" class="flex items-center px-4 py-3 text-primary bg-primary/5 border-l-4 border-primary">
                            <i class="fa fa-tachometer w-6"></i>
                            <span>控制台</span>
                        </a>
                    </li>
                    <li class="mb-1">
                        <a href="#robots" class="flex items-center px-4 py-3 text-dark-2 hover:bg-light-1 transition-colors">
                            <i class="fa fa-cogs w-6"></i>
                            <span>机器人列表</span>
                        </a>
                    </li>
                    <li class="mb-1">
                        <a href="#tasks" class="flex items-center px-4 py-3 text-dark-2 hover:bg-light-1 transition-colors">
                            <i class="fa fa-tasks w-6"></i>
                            <span>任务管理</span>
                        </a>
                    </li>
                    <li class="mb-1">
                        <a href="#logs" class="flex items-center px-4 py-3 text-dark-2 hover:bg-light-1 transition-colors">
                            <i class="fa fa-history w-6"></i>
                            <span>运行日志</span>
                        </a>
                    </li>
                    <li class="mb-1">
                        <a href="#settings" class="flex items-center px-4 py-3 text-dark-2 hover:bg-light-1 transition-colors">
                            <i class="fa fa-cog w-6"></i>
                            <span>系统设置</span>
                        </a>
                    </li>
                </ul>
            </nav>
            
            <div class="absolute bottom-0 w-full p-4 border-t border-light-2">
                <div class="flex items-center space-x-3">
                    <img src="https://picsum.photos/id/1005/40/40" alt="用户头像" class="w-10 h-10 rounded-full object-cover">
                    <div>
                        <p class="font-medium">管理员</p>
                        <p class="text-xs text-dark-2">admin@robot.com</p>
                    </div>
                    <button class="ml-auto text-dark-2 hover:text-danger transition-colors">
                        <i class="fa fa-sign-out"></i>
                    </button>
                </div>
            </div>
        </aside>

        <!-- 遮罩层 -->
        <div id="sidebar-overlay" class="fixed inset-0 bg-dark/50 z-10 lg:hidden hidden"></div>

        <!-- 主内容区 -->
        <div class="flex-1 flex flex-col overflow-hidden lg:ml-0">
            <!-- 顶部导航 -->
            <header class="bg-white card-shadow p-4 flex items-center justify-between sticky top-0 z-10">
                <button id="mobile-menu-btn" class="lg:hidden text-dark-2 mr-4">
                    <i class="fa fa-bars text-xl"></i>
                </button>
                
                <div class="flex items-center space-x-4 flex-1 max-w-md">
                    <div class="relative w-full">
                        <input type="text" id="search-input" placeholder="搜索机器人、任务..." 
                               class="w-full pl-10 pr-4 py-2 rounded-lg border border-light-2 form-input-focus">
                        <i class="fa fa-search absolute left-3 top-1/2 -translate-y-1/2 text-dark-2"></i>
                    </div>
                </div>
                
                <div class="flex items-center space-x-4">
                    <button class="relative text-dark-2 hover:text-primary transition-colors p-2">
                        <i class="fa fa-bell text-xl"></i>
                        <span class="absolute top-0 right-0 w-2 h-2 bg-danger rounded-full"></span>
                    </button>
                    <button class="relative text-dark-2 hover:text-primary transition-colors p-2">
                        <i class="fa fa-envelope text-xl"></i>
                        <span class="absolute top-0 right-0 w-2 h-2 bg-warning rounded-full"></span>
                    </button>
                </div>
            </header>

            <!-- 内容区域 -->
            <main class="flex-1 overflow-y-auto p-4 md:p-6 bg-light-1">
                <!-- 状态概览 -->
                <section class="mb-6" id="stats-overview">
                    <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4">
                        <!-- 总机器人 -->
                        <div class="bg-white rounded-xl p-5 card-shadow hover-scale">
                            <div class="flex justify-between items-start">
                                <div>
                                    <p class="text-dark-2 text-sm mb-1">总机器人</p>
                                    <h3 class="text-2xl font-bold" id="total-robots">0</h3>
                                </div>
                                <div class="w-10 h-10 rounded-lg bg-primary/10 flex items-center justify-center text-primary">
                                    <i class="fa fa-robot"></i>
                                </div>
                            </div>
                            <div class="mt-4 flex items-center text-sm">
                                <span class="text-success flex items-center">
                                    <i class="fa fa-arrow-up mr-1"></i> <span id="total-robots-change">0</span>%
                                </span>
                                <span class="text-dark-2 ml-2">较上月</span>
                            </div>
                        </div>
                        
                        <!-- 在线机器人 -->
                        <div class="bg-white rounded-xl p-5 card-shadow hover-scale">
                            <div class="flex justify-between items-start">
                                <div>
                                    <p class="text-dark-2 text-sm mb-1">在线机器人</p>
                                    <h3 class="text-2xl font-bold" id="online-robots">0</h3>
                                </div>
                                <div class="w-10 h-10 rounded-lg bg-success/10 flex items-center justify-center text-success">
                                    <i class="fa fa-check-circle"></i>
                                </div>
                            </div>
                            <div class="mt-4 flex items-center text-sm">
                                <span class="text-success flex items-center">
                                    <i class="fa fa-arrow-up mr-1"></i> <span id="online-robots-change">0</span>%
                                </span>
                                <span class="text-dark-2 ml-2">较上月</span>
                            </div>
                        </div>
                        
                        <!-- 运行中任务 -->
                        <div class="bg-white rounded-xl p-5 card-shadow hover-scale">
                            <div class="flex justify-between items-start">
                                <div>
                                    <p class="text-dark-2 text-sm mb-1">运行中任务</p>
                                    <h3 class="text-2xl font-bold" id="running-tasks">0</h3>
                                </div>
                                <div class="w-10 h-10 rounded-lg bg-warning/10 flex items-center justify-center text-warning">
                                    <i class="fa fa-spinner"></i>
                                </div>
                            </div>
                            <div class="mt-4 flex items-center text-sm">
                                <span class="text-danger flex items-center">
                                    <i class="fa fa-arrow-down mr-1"></i> <span id="running-tasks-change">0</span>%
                                </span>
                                <span class="text-dark-2 ml-2">较上月</span>
                            </div>
                        </div>
                        
                        <!-- 任务完成率 -->
                        <div class="bg-white rounded-xl p-5 card-shadow hover-scale">
                            <div class="flex justify-between items-start">
                                <div>
                                    <p class="text-dark-2 text-sm mb-1">任务完成率</p>
                                    <h3 class="text-2xl font-bold" id="completion-rate">0%</h3>
                                </div>
                                <div class="w-10 h-10 rounded-lg bg-secondary/10 flex items-center justify-center text-secondary">
                                    <i class="fa fa-bar-chart"></i>
                                </div>
                            </div>
                            <div class="mt-4 flex items-center text-sm">
                                <span class="text-success flex items-center">
                                    <i class="fa fa-arrow-up mr-1"></i> <span id="completion-rate-change">0</span>%
                                </span>
                                <span class="text-dark-2 ml-2">较上月</span>
                            </div>
                        </div>
                    </div>
                </section>

                <!-- 图表和机器人列表 -->
                <section class="grid grid-cols-1 lg:grid-cols-3 gap-6 mb-6">
                    <!-- 活跃度图表 -->
                    <div class="lg:col-span-2 bg-white rounded-xl p-5 card-shadow">
                        <div class="flex justify-between items-center mb-6">
                            <h2 class="text-lg font-bold">机器人活跃度趋势</h2>
                            <div class="flex space-x-2">
                                <button class="px-3 py-1 text-sm bg-primary text-white rounded-md" id="daily-trend">日</button>
                                <button class="px-3 py-1 text-sm text-dark-2 hover:bg-light-1 rounded-md transition-colors" id="weekly-trend">周</button>
                                <button class="px-3 py-1 text-sm text-dark-2 hover:bg-light-1 rounded-md transition-colors" id="monthly-trend">月</button>
                            </div>
                        </div>
                        <div class="h-80">
                            <canvas id="activityChart"></canvas>
                        </div>
                    </div>

                    <!-- 机器人状态分布 -->
                    <div class="bg-white rounded-xl p-5 card-shadow">
                        <h2 class="text-lg font-bold mb-6">机器人状态分布</h2>
                        <div class="h-64 flex items-center justify-center">
                            <canvas id="statusChart"></canvas>
                        </div>
                        <div class="grid grid-cols-2 gap-2 mt-4">
                            <div class="flex items-center">
                                <span class="w-3 h-3 rounded-full bg-success mr-2"></span>
                                <span class="text-sm">在线 (<span id="status-online">0</span>)</span>
                            </div>
                            <div class="flex items-center">
                                <span class="w-3 h-3 rounded-full bg-danger mr-2"></span>
                                <span class="text-sm">离线 (<span id="status-offline">0</span>)</span>
                            </div>
                            <div class="flex items-center">
                                <span class="w-3 h-3 rounded-full bg-warning mr-2"></span>
                                <span class="text-sm">维护中 (<span id="status-maintenance">0</span>)</span>
                            </div>
                            <div class="flex items-center">
                                <span class="w-3 h-3 rounded-full bg-primary mr-2"></span>
                                <span class="text-sm">待机 (<span id="status-idle">0</span>)</span>
                            </div>
                        </div>
                    </div>
                </section>

                <!-- 机器人列表 -->
                <section class="bg-white rounded-xl p-5 card-shadow">
                    <div class="flex flex-col md:flex-row md:items-center md:justify-between mb-6">
                        <h2 class="text-lg font-bold mb-4 md:mb-0">机器人列表</h2>
                        <div class="flex flex-col sm:flex-row gap-3">
                            <div class="relative">
                                <select id="status-filter" class="pl-4 pr-10 py-2 rounded-lg border border-light-2 form-input-focus appearance-none bg-white">
                                    <option value="">全部状态</option>
                                    <option value="online">在线</option>
                                    <option value="offline">离线</option>
                                    <option value="maintenance">维护中</option>
                                </select>
                                <i class="fa fa-chevron-down absolute right-3 top-1/2 -translate-y-1/2 text-dark-2 pointer-events-none"></i>
                            </div>
                            <!-- 新增机器人按钮 - 点击打开模态框 -->
                            <button id="add-robot-btn" class="px-4 py-2 bg-primary text-white rounded-lg hover:bg-primary/90 transition-colors flex items-center">
                                <i class="fa fa-plus mr-2"></i> 新增机器人
                            </button>
                        </div>
                    </div>

                    <div class="overflow-x-auto">
                        <table class="w-full min-w-[640px]">
                            <thead>
                                <tr class="border-b border-light-2">
                                    <th class="text-left py-3 px-4 font-medium text-dark-2">机器人名称</th>
                                    <th class="text-left py-3 px-4 font-medium text-dark-2">ID</th>
                                    <th class="text-left py-3 px-4 font-medium text-dark-2">类型</th>
                                    <th class="text-left py-3 px-4 font-medium text-dark-2">状态</th>
                                    <th class="text-left py-3 px-4 font-medium text-dark-2">最后活动</th>
                                    <th class="text-left py-3 px-4 font-medium text-dark-2">任务进度</th>
                                    <th class="text-left py-3 px-4 font-medium text-dark-2">操作</th>
                                </tr>
                            </thead>
                            <tbody id="robot-table-body">
                                <!-- 机器人列表将通过JavaScript动态加载 -->
                                <tr>
                                    <td colspan="7" class="py-8 text-center text-dark-2">
                                        <i class="fa fa-spinner fa-spin mr-2"></i> 加载中...
                                    </td>
                                </tr>
                            </tbody>
                        </table>
                    </div>

                    <!-- 分页 -->
                    <div class="flex flex-col sm:flex-row justify-between items-center mt-6" id="pagination-container">
                        <div class="text-sm text-dark-2 mb-4 sm:mb-0">
                            显示 <span id="showing-range">0-0</span> 条，共 <span id="total-count">0</span> 条
                        </div>
                        <div class="flex items-center space-x-1">
                            <button id="prev-page" class="w-8 h-8 flex items-center justify-center rounded border border-light-2 text-dark-2 hover:border-primary hover:text-primary transition-colors disabled:opacity-50 disabled:cursor-not-allowed" disabled>
                                <i class="fa fa-chevron-left text-xs"></i>
                            </button>
                            <div id="page-numbers" class="flex items-center space-x-1">
                                <!-- 页码将通过JavaScript动态加载 -->
                            </div>
                            <button id="next-page" class="w-8 h-8 flex items-center justify-center rounded border border-light-2 text-dark-2 hover:border-primary hover:text-primary transition-colors disabled:opacity-50 disabled:cursor-not-allowed" disabled>
                                <i class="fa fa-chevron-right text-xs"></i>
                            </button>
                        </div>
                    </div>
                </section>
            </main>
        </div>
    </div>

    <!-- 添加机器人模态框 -->
    <div id="add-robot-modal" class="fixed inset-0 z-50 flex items-center justify-center hidden">
        <!-- 遮罩层 -->
        <div class="absolute inset-0 bg-dark/50 backdrop-blur-sm" id="modal-overlay"></div>
        
        <!-- 模态框内容 -->
        <div class="relative-5 bg-white rounded-xl w-full max-w-2xl max-h-[90vh] overflow-y-auto modal-enter relative z-10">
            <div class="flex justify-between items-center p-5 border-b border-light-2 sticky top-0 bg-white">
                <h3 class="text-xl font-bold">新增机器人</h3>
                <button id="close-modal-btn" class="text-dark-2 hover:text-dark transition-colors">
                    <i class="fa fa-times text-lg"></i>
                </button>
            </div>
            
            <form id="add-robot-form" class="p-5 space-y-6">
                <!-- 基本信息 -->
                <div class="space-y-4">
                    <h4 class="text-lg font-medium">基本信息</h4>
                    
                    <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                        <!-- 机器人名称 -->
                        <div class="space-y-2">
                            <label for="robot-name" class="block text-sm font-medium text-dark-2">
                                机器人名称 <span class="text-danger">*</span>
                            </label>
                            <input type="text" id="robot-name" name="robot-name" 
                                   class="w-full px-4 py-2 rounded-lg border border-light-2 form-input-focus"
                                   placeholder="例如：清洁机器人-05" required>
                        </div>
                        
                        <!-- 机器人ID -->
                        <div class="space-y-2">
                            <label for="robot-id" class="block text-sm font-medium text-dark-2">
                                机器人ID <span class="text-danger">*</span>
                            </label>
                            <div class="relative">
                                <input type="text" id="robot-id" name="robot-id" 
                                       class="w-full px-4 py-2 rounded-lg border border-light-2 form-input-focus"
                                       placeholder="自动生成，可修改" required>
                                <button type="button" class="absolute right-3 top-1/2 -translate-y-1/2 text-primary hover:text-primary/80 transition-colors" id="generate-id-btn">
                                    <i class="fa fa-refresh"></i>
                                </button>
                            </div>
                        </div>
                    </div>
                    
                    <!-- 机器人类型 -->
                    <div class="space-y-2">
                        <label class="block text-sm font-medium text-dark-2">
                            机器人类型 <span class="text-danger">*</span>
                        </label>
                        <div class="grid grid-cols-2 sm:grid-cols-4 gap-3">
                            <label class="flex flex-col items-center p-3 border border-light-2 rounded-lg cursor-pointer hover:border-primary hover:bg-primary/5 transition-colors group">
                                <input type="radio" name="robot-type" value="cleaning" class="sr-only" required>
                                <div class="w-10 h-10 rounded-full bg-primary/10 flex items-center justify-center text-primary mb-2 group-hover:bg-primary group-hover:text-white transition-colors">
                                    <i class="fa fa-broom"></i>
                                </div>
                                <span class="text-sm">清洁型</span>
                            </label>
                            
                            <label class="flex flex-col items-center p-3 border border-light-2 rounded-lg cursor-pointer hover:border-primary hover:bg-primary/5 transition-colors group">
                                <input type="radio" name="robot-type" value="transport" class="sr-only">
                                <div class="w-10 h-10 rounded-full bg-secondary/10 flex items-center justify-center text-secondary mb-2 group-hover:bg-secondary group-hover:text-white transition-colors">
                                    <i class="fa fa-truck"></i>
                                </div>
                                <span class="text-sm">搬运型</span>
                            </label>
                            
                            <label class="flex flex-col items-center p-3 border border-light-2 rounded-lg cursor-pointer hover:border-primary hover:bg-primary/5 transition-colors group">
                                <input type="radio" name="robot-type" value="inspection" class="sr-only">
                                <div class="w-10 h-10 rounded-full bg-warning/10 flex items-center justify-center text-warning mb-2 group-hover:bg-warning group-hover:text-white transition-colors">
                                    <i class="fa fa-search"></i>
                                </div>
                                <span class="text-sm">巡检型</span>
                            </label>
                            
                            <label class="flex flex-col items-center p-3 border border-light-2 rounded-lg cursor-pointer hover:border-primary hover:bg-primary/5 transition-colors group">
                                <input type="radio" name="robot-type" value="delivery" class="sr-only">
                                <div class="w-10 h-10 rounded-full bg-danger/10 flex items-center justify-center text-danger mb-2 group-hover:bg-danger group-hover:text-white transition-colors">
                                    <i class="fa fa-shopping-bag"></i>
                                </div>
                                <span class="text-sm">配送型</span>
                            </label>
                        </div>
                    </div>
                    
                    <!-- 机器人描述 -->
                    <div class="space-y-2">
                        <label for="robot-description" class="block text-sm font-medium text-dark-2">
                            机器人描述
                        </label>
                        <textarea id="robot-description" name="robot-description" rows="3"
                                  class="w-full px-4 py-2 rounded-lg border border-light-2 form-input-focus"
                                  placeholder="描述机器人的功能、用途等信息"></textarea>
                    </div>
                </div>
                
                <!-- 网络配置 -->
                <div class="space-y-4">
                    <h4 class="text-lg font-medium">网络配置</h4>
                    
                    <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                        <!-- IP地址 -->
                        <div class="space-y-2">
                            <label for="robot-ip" class="block text-sm font-medium text-dark-2">
                                IP地址 <span class="text-danger">*</span>
                            </label>
                            <input type="text" id="robot-ip" name="robot-ip" 
                                   class="w-full px-4 py-2 rounded-lg border border-light-2 form-input-focus"
                                   placeholder="例如：192.168.1.100" required>
                        </div>
                        
                        <!-- 端口号 -->
                        <div class="space-y-2">
                            <label for="robot-port" class="block text-sm font-medium text-dark-2">
                                端口号 <span class="text-danger">*</span>
                            </label>
                            <input type="number" id="robot-port" name="robot-port" min="1" max="65535"
                                   class="w-full px-4 py-2 rounded-lg border border-light-2 form-input-focus"
                                   value="8080" required>
                        </div>
                    </div>
                    
                    <!-- 通信协议 -->
                    <div class="space-y-2">
                        <label for="robot-protocol" class="block text-sm font-medium text-dark-2">
                            通信协议 <span class="text-danger">*</span>
                        </label>
                        <select id="robot-protocol" name="robot-protocol"
                                class="w-full px-4 py-2 rounded-lg border border-light-2 form-input-focus" required>
                            <option value="">请选择通信协议</option>
                            <option value="mqtt">MQTT</option>
                            <option value="http">HTTP</option>
                            <option value="websocket">WebSocket</option>
                            <option value="tcp">TCP/IP</option>
                        </select>
                    </div>
                </div>
                
                <!-- 硬件参数 -->
                <div class="space-y-4">
                    <h4 class="text-lg font-medium">硬件参数</h4>
                    
                    <div class="grid grid-cols-1 md:grid-cols-3 gap-4">
                        <!-- 电池容量 -->
                        <div class="space-y-2">
                            <label for="battery-capacity" class="block text-sm font-medium text-dark-2">
                                电池容量 (mAh)
                            </label>
                            <input type="number" id="battery-capacity" name="battery-capacity" min="0"
                                   class="w-full px-4 py-2 rounded-lg border border-light-2 form-input-focus"
                                   placeholder="例如：5000">
                        </div>
                        
                        <!-- 最大负载 -->
                        <div class="space-y-2">
                            <label for="max-load" class="block text-sm font-medium text-dark-2">
                                最大负载 (kg)
                            </label>
                            <input type="number" id="max-load" name="max-load" min="0" step="0.1"
                                   class="w-full px-4 py-2 rounded-lg border border-light-2 form-input-focus"
                                   placeholder="例如：5.0">
                        </div>
                        
                        <!-- 移动速度 -->
                        <div class="space-y-2">
                            <label for="move-speed" class="block text-sm font-medium text-dark-2">
                                移动速度 (m/s)
                            </label>
                            <input type="number" id="move-speed" name="move-speed" min="0" step="0.1"
                                   class="w-full px-4 py-2 rounded-lg border border-light-2 form-input-focus"
                                   placeholder="例如：1.2">
                        </div>
                    </div>
                </div>
                
                <!-- 初始状态 -->
                <div class="space-y-2">
                    <label class="block text-sm font-medium text-dark-2">
                        初始状态 <span class="text-danger">*</span>
                    </label>
                    <div class="flex flex-wrap gap-3">
                        <label class="inline-flex items-center space-x-2 px-4 py-2 border border-light-2 rounded-lg cursor-pointer hover:border-primary hover:bg-primary/5 transition-colors">
                            <input type="radio" name="initial-status" value="online" class="text-primary" required>
                            <span>在线</span>
                        </label>
                        
                        <label class="inline-flex items-center space-x-2 px-4 py-2 border border-light-2 rounded-lg cursor-pointer hover:border-primary hover:bg-primary/5 transition-colors">
                            <input type="radio" name="initial-status" value="offline" class="text-primary">
                            <span>离线</span>
                        </label>
                        
                        <label class="inline-flex items-center space-x-2 px-4 py-2 border border-light-2 rounded-lg cursor-pointer hover:border-primary hover:bg-primary/5 transition-colors">
                            <input type="radio" name="initial-status" value="maintenance" class="text-primary">
                            <span>维护中</span>
                        </label>
                    </div>
                </div>
                
                <!-- 提交按钮 -->
                <div class="flex justify-end space-x-3 pt-4 border-t border-light-2">
                    <button type="button" id="cancel-add-btn" class="px-4 py-2 border border-light-2 rounded-lg hover:bg-light-1 transition-colors">
                        取消
                    </button>
                    <button type="submit" class="px-4 py-2 bg-primary text-white rounded-lg hover:bg-primary/90 transition-colors flex items-center">
                        <i class="fa fa-save mr-2"></i> 保存机器人
                    </button>
                </div>
            </form>
        </div>
    </div>

    <!-- 成功提示弹窗 -->
    <div id="success-toast" class="fixed bottom-6 right-6 bg-success text-white px-4 py-3 rounded-lg shadow-lg flex items-center space-x-2 transform translate-y-20 opacity-0 transition-all duration-300 z-50">
        <i class="fa fa-check-circle text-xl"></i>
        <span id="toast-message">操作成功！</span>
    </div>

    <!-- 确认删除模态框 -->
    <div id="confirm-delete-modal" class="fixed inset-0 z-50 flex items-center justify-center hidden">
        <div class="absolute inset-0 bg-dark/50 backdrop-blur-sm" id="delete-modal-overlay"></div>
        <div class="relative bg-white rounded-xl w-full max-w-md p-6 modal-enter z-10">
            <h3 class="text-lg font-bold mb-4">确认删除</h3>
            <p class="text-dark-2 mb-6">
                您确定要删除机器人 <span id="delete-robot-name" class="font-medium"></span> (ID: <span id="delete-robot-id"></span>) 吗？
                此操作不可撤销，相关任务也将被删除。
            </p>
            <div class="flex justify-end space-x-3">
                <button id="cancel-delete-btn" class="px-4 py-2 border border-light-2 rounded-lg hover:bg-light-1 transition-colors">
                    取消
                </button>
                <button id="confirm-delete-btn" class="px-4 py-2 bg-danger text-white rounded-lg hover:bg-danger/90 transition-colors">
                    确认删除
                </button>
            </div>
        </div>
    </div>

    <script>
        // 全局变量
        let currentPage = 1;
        let totalPages = 1;
        let currentStatusFilter = '';
        let currentSearchQuery = '';
        let deleteRobotId = null;
        
        // 侧边栏交互
        const sidebar = document.getElementById('sidebar');
        const sidebarOverlay = document.getElementById('sidebar-overlay');
        const mobileMenuBtn = document.getElementById('mobile-menu-btn');
        const sidebarToggle = document.getElementById('sidebar-toggle');

        function showSidebar() {
            sidebar.classList.remove('-translate-x-full');
            sidebarOverlay.classList.remove('hidden');
            document.body.classList.add('overflow-hidden');
        }

        function hideSidebar() {
            sidebar.classList.add('-translate-x-full');
            sidebarOverlay.classList.add('hidden');
            document.body.classList.remove('overflow-hidden');
        }

        mobileMenuBtn.addEventListener('click', showSidebar);
        sidebarToggle.addEventListener('click', hideSidebar);
        sidebarOverlay.addEventListener('click', hideSidebar);

        // API请求函数
        async function apiRequest(url, method = 'GET', data = null) {
            try {
                const options = {
                    method: method,
                    headers: {
                        'Content-Type': 'application/json',
                    },
                };

                if (data && (method === 'POST' || method === 'PUT')) {
                    options.body = JSON.stringify(data);
                }

                const response = await fetch(url, options);
                const result = await response.json();

                if (!response.ok) {
                    throw new Error(result.message || 'API请求失败');
                }

                return result;
            } catch (error) {
                showToast(error.message, 'error');
                console.error('API请求错误:', error);
                throw error;
            }
        }

        // 显示提示框
        function showToast(message, type = 'success') {
            const toast = document.getElementById('success-toast');
            const toastMessage = document.getElementById('toast-message');
            
            toastMessage.textContent = message;
            
            if (type === 'error') {
                toast.classList.remove('bg-success');
                toast.classList.add('bg-danger');
            } else {
                toast.classList.remove('bg-danger');
                toast.classList.add('bg-success');
            }
            
            toast.classList.remove('translate-y-20', 'opacity-0');
            
            // 3秒后隐藏
            setTimeout(() => {
                toast.classList.add('translate-y-20', 'opacity-0');
            }, 3000);
        }

        // 加载统计数据
        async function loadStatistics() {
            try {
                const result = await apiRequest('/api/robots/statistics');
                const stats = result.data.summary;
                
                // 更新统计卡片
                document.getElementById('total-robots').textContent = stats.total_robots;
                document.getElementById('online-robots').textContent = stats.online_robots;
                document.getElementById('running-tasks').textContent = stats.running_tasks;
                document.getElementById('completion-rate').textContent = `${stats.completion_rate}%`;
                
                // 更新状态分布
                document.getElementById('status-online').textContent = stats.online_robots;
                document.getElementById('status-offline').textContent = stats.offline_robots;
                document.getElementById('status-maintenance').textContent = stats.maintenance_robots;
                // 计算待机数量（总在线数 - 运行中任务对应的机器人）
                const idleCount = Math.max(0, stats.online_robots - Math.min(stats.running_tasks, stats.online_robots));
                document.getElementById('status-idle').textContent = idleCount;
                
                // 随机生成百分比变化（模拟数据）
                document.getElementById('total-robots-change').textContent = (Math.random() * 10 + 5).toFixed(1);
                document.getElementById('online-robots-change').textContent = (Math.random() * 15 + 8).toFixed(1);
                document.getElementById('running-tasks-change').textContent = (Math.random() * 5 + 2).toFixed(1);
                document.getElementById('completion-rate-change').textContent = (Math.random() * 6 + 3).toFixed(1);
                
                // 初始化图表
                initCharts(result.data.activity_trend);
                
            } catch (error) {
                console.error('加载统计数据失败:', error);
            }
        }

        // 初始化图表
        function initCharts(activityData) {
            // 活跃度趋势图表
            const activityCtx = document.getElementById('activityChart').getContext('2d');
            const activityChart = new Chart(activityCtx, {
                type: 'line',
                data: {
                    labels: activityData.hours,
                    datasets: [
                        {
                            label: '在线机器人',
                            data: activityData.online_robots,
                            borderColor: '#165DFF',
                            backgroundColor: 'rgba(22, 93, 255, 0.1)',
                            tension: 0.4,
                            fill: true
                        },
                        {
                            label: '活跃任务',
                            data: activityData.active_tasks,
                            borderColor: '#36CFC9',
                            backgroundColor: 'rgba(54, 207, 201, 0.1)',
                            tension: 0.4,
                            fill: true
                        }
                    ]
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: false,
                    plugins: {
                        legend: {
                            position: 'top',
                            labels: {
                                boxWidth: 12,
                                usePointStyle: true,
                                pointStyle: 'circle'
                            }
                        },
                        tooltip: {
                            mode: 'index',
                            intersect: false
                        }
                    },
                    scales: {
                        y: {
                            beginAtZero: true,
                            grid: {
                                color: 'rgba(0, 0, 0, 0.05)'
                            }
                        },
                        x: {
                            grid: {
                                display: false
                            }
                        }
                    },
                    interaction: {
                        mode: 'nearest',
                        axis: 'x',
                        intersect: false
                    }
                }
            });

            // 机器人状态分布图表
            const statusCtx = document.getElementById('statusChart').getContext('2d');
            
            // 获取状态数据
            const online = parseInt(document.getElementById('status-online').textContent);
            const offline = parseInt(document.getElementById('status-offline').textContent);
            const maintenance = parseInt(document.getElementById('status-maintenance').textContent);
            const idle = parseInt(document.getElementById('status-idle').textContent);
            
            const statusChart = new Chart(statusCtx, {
                type: 'doughnut',
                data: {
                    labels: ['在线', '离线', '维护中', '待机'],
                    datasets: [{
                        data: [online, offline, maintenance, idle],
                        backgroundColor: [
                            '#52C41A',
                            '#FF4D4F',
                            '#FAAD14',
                            '#165DFF'
                        ],
                        borderWidth: 0,
                        hoverOffset: 4
                    }]
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: false,
                    cutout: '70%',
                    plugins: {
                        legend: {
                            display: false
                        },
                        tooltip: {
                            callbacks: {
                                label: function(context) {
                                    const label = context.label || '';
                                    const value = context.raw || 0;
                                    const total = context.dataset.data.reduce((a, b) => a + b, 0);
                                    const percentage = Math.round((value / total) * 100);
                                    return `${label}: ${value} 台 (${percentage}%)`;
                                }
                            }
                        }
                    }
                }
            });
        }

        // 加载机器人列表
        async function loadRobots(page = 1, status = '', search = '') {
            try {
                // 显示加载状态
                const tableBody = document.getElementById('robot-table-body');
                tableBody.innerHTML = `
                    <tr>
                        <td colspan="7" class="py-8 text-center text-dark-2">
                            <i class="fa fa-spinner fa-spin mr-2"></i> 加载中...
                        </td>
                    </tr>
                `;
                
                // 构建查询参数
                const params = new URLSearchParams();
                params.append('page', page);
                params.append('per_page', 10);
                if (status) params.append('status', status);
                
                let url = `/api/robots?${params.toString()}`;
                if (search) {
                    url += `&search=${encodeURIComponent(search)}`;
                }
                
                const result = await apiRequest(url);
                const robots = result.data;
                const pagination = result.pagination;
                
                currentPage = pagination.page;
                totalPages = pagination.pages;
                currentStatusFilter = status;
                currentSearchQuery = search;
                
                // 更新表格内容
                if (robots.length === 0) {
                    tableBody.innerHTML = `
                        <tr>
                            <td colspan="7" class="py-8 text-center text-dark-2">
                                <i class="fa fa-search mr-2"></i> 未找到匹配的机器人
                            </td>
                        </tr>
                    `;
                } else {
                    tableBody.innerHTML = '';
                    robots.forEach(robot => {
                        // 获取任务进度（假设每个机器人至少有一个任务）
                        let progress = 0;
                        let progressText = '0%';
                        
                        // 模拟任务进度数据
                        if (robot.status === 'online') {
                            progress = Math.floor(Math.random() * 101);
                            progressText = `${progress}%`;
                        } else if (robot.status === 'maintenance') {
                            progressText = '暂停中';
                        } else {
                            progress = Math.floor(Math.random() * 51);
                            progressText = `${progress}% (未完成)`;
                        }
                        
                        // 状态样式
                        let statusClass = 'bg-dark-2';
                        let statusText = robot.status_name;
                        
                        if (robot.status === 'online') {
                            statusClass = 'bg-success';
                        } else if (robot.status === 'offline') {
                            statusClass = 'bg-danger';
                        } else if (robot.status === 'maintenance') {
                            statusClass = 'bg-warning';
                        }
                        
                        // 类型样式
                        let typeClass = 'bg-primary/10 text-primary';
                        if (robot.type === 'transport') {
                            typeClass = 'bg-secondary/10 text-secondary';
                        } else if (robot.type === 'inspection') {
                            typeClass = 'bg-warning/10 text-warning';
                        } else if (robot.type === 'delivery') {
                            typeClass = 'bg-danger/10 text-danger';
                        }
                        
                        // 机器人图片（根据类型选择不同图片）
                        let robotImageId = 1011; // 默认图片
                        if (robot.type === 'transport') robotImageId = 1025;
                        if (robot.type === 'inspection') robotImageId = 1074;
                        if (robot.type === 'delivery') robotImageId = 1062;
                        
                        const row = document.createElement('tr');
                        row.className = 'border-b border-light-2 hover:bg-light-1/50 transition-colors';
                        row.innerHTML = `
                            <td class="py-4 px-4">
                                <div class="flex items-center">
                                    <img src="https://picsum.photos/id/${robotImageId}/40/40" alt="${robot.name}图片" class="w-8 h-8 rounded-md mr-3">
                                    <span>${robot.name}</span>
                                </div>
                            </td>
                            <td class="py-4 px-4 text-dark-2">${robot.robot_id}</td>
                            <td class="py-4 px-4">
                                <span class="px-2 py-1 ${typeClass} text-xs rounded-full">${robot.type_name}</span>
                            </td>
                            <td class="py-4 px-4">
                                <span class="flex items-center">
                                    <span class="w-2 h-2 ${statusClass} rounded-full mr-2"></span>
                                    ${statusText}
                                </span>
                            </td>
                            <td class="py-4 px-4 text-dark-2">${robot.last_active}</td>
                            <td class="py-4 px-4">
                                <div class="w-full bg-light-2 rounded-full h-2">
                                    <div class="bg-${status === 'maintenance' ? 'warning' : 'success'} h-2 rounded-full progress-bar" style="width: ${progress}%"></div>
                                </div>
                                <span class="text-xs text-dark-2 mt-1 block">${progressText}</span>
                            </td>
                            <td class="py-4 px-4">
                                <div class="flex space-x-2">
                                    <button class="text-primary hover:text-primary/80 transition-colors view-robot" data-id="${robot.id}" title="查看详情">
                                        <i class="fa fa-eye"></i>
                                    </button>
                                    <button class="text-warning hover:text-warning/80 transition-colors ${robot.status === 'online' ? '' : 'text-dark-2 cursor-not-allowed'}" 
                                            data-id="${robot.id}" ${robot.status !== 'online' ? 'disabled' : ''} title="${robot.status === 'online' ? '发送指令' : '离线/维护中无法操作'}">
                                        <i class="fa fa-commenting"></i>
                                    </button>
                                    <button class="text-danger hover:text-danger/80 transition-colors delete-robot" 
                                            data-id="${robot.id}" data-name="${robot.name}" data-robot-id="${robot.robot_id}" title="删除机器人">
                                        <i class="fa fa-trash"></i>
                                    </button>
                                </div>
                            </td>
                        `;
                        tableBody.appendChild(row);
                    });
                }
                
                // 更新分页控件
                updatePagination(pagination);
                
                // 绑定删除按钮事件
                document.querySelectorAll('.delete-robot').forEach(btn => {
                    btn.addEventListener('click', function() {
                        const robotId = this.getAttribute('data-id');
                        const robotName = this.getAttribute('data-name');
                        const robotUniqueId = this.getAttribute('data-robot-id');
                        
                        showDeleteConfirmation(robotId, robotName, robotUniqueId);
                    });
                });
                
                // 绑定查看详情按钮事件
                document.querySelectorAll('.view-robot').forEach(btn => {
                    btn.addEventListener('click', function() {
                        const robotId = this.getAttribute('data-id');
                        viewRobotDetails(robotId);
                    });
                });
                
            } catch (error) {
                console.error('加载机器人列表失败:', error);
                const tableBody = document.getElementById('robot-table-body');
                tableBody.innerHTML = `
                    <tr>
                        <td colspan="7" class="py-8 text-center text-danger">
                            <i class="fa fa-exclamation-circle mr-2"></i> 加载失败，请刷新页面重试
                        </td>
                    </tr>
                `;
            }
        }

        // 更新分页控件
        function updatePagination(pagination) {
            const pageNumbers = document.getElementById('page-numbers');
            const prevPageBtn = document.getElementById('prev-page');
            const nextPageBtn = document.getElementById('next-page');
            const showingRange = document.getElementById('showing-range');
            const totalCount = document.getElementById('total-count');
            
            // 更新显示范围和总数
            const start = (pagination.page - 1) * pagination.per_page + 1;
            const end = Math.min(start + pagination.per_page - 1, pagination.total);
            showingRange.textContent = `${start}-${end}`;
            totalCount.textContent = pagination.total;
            
            // 更新页码按钮
            pageNumbers.innerHTML = '';
            
            // 只显示当前页附近的页码（最多显示5个）
            let startPage = Math.max(1, pagination.page - 2);
            let endPage = Math.min(pagination.pages, startPage + 4);
            
            // 如果总页数少于5个，调整显示范围
            if (pagination.pages <= 5) {
                startPage = 1;
                endPage = pagination.pages;
            }
            
            for (let i = startPage; i <= endPage; i++) {
                const pageBtn = document.createElement('button');
                pageBtn.className = `w-8 h-8 flex items-center justify-center rounded ${i === pagination.page ? 'bg-primary text-white' : 'border border-light-2 text-dark-2 hover:border-primary hover:text-primary transition-colors'}`;
                pageBtn.textContent = i;
                pageBtn.addEventListener('click', () => loadRobots(i, currentStatusFilter, currentSearchQuery));
                pageNumbers.appendChild(pageBtn);
            }
            
            // 更新上一页/下一页按钮状态
            prevPageBtn.disabled = !pagination.has_prev;
            nextPageBtn.disabled = !pagination.has_next;
            
            prevPageBtn.onclick = pagination.has_prev ? () => loadRobots(pagination.page - 1, currentStatusFilter, currentSearchQuery) : null;
            nextPageBtn.onclick = pagination.has_next ? () => loadRobots(pagination.page + 1, currentStatusFilter, currentSearchQuery) : null;
        }

        // 显示删除确认
        function showDeleteConfirmation(robotId, robotName, robotUniqueId) {
            deleteRobotId = robotId;
            
            const deleteModal = document.getElementById('confirm-delete-modal');
            document.getElementById('delete-robot-name').textContent = robotName;
            document.getElementById('delete-robot-id').textContent = robotUniqueId;
            
            deleteModal.classList.remove('hidden');
            document.body.classList.add('overflow-hidden');
        }

        // 隐藏删除确认
        function hideDeleteConfirmation() {
            const deleteModal = document.getElementById('confirm-delete-modal');
            deleteModal.classList.add('hidden');
            document.body.classList.remove('overflow-hidden');
            deleteRobotId = null;
        }

        // 确认删除机器人
        async function confirmDeleteRobot() {
            if (!deleteRobotId) return;
            
            try {
                await apiRequest(`/api/robots/${deleteRobotId}`, 'DELETE');
                hideDeleteConfirmation();
                showToast('机器人删除成功！');
                // 重新加载机器人列表
                loadRobots(currentPage, currentStatusFilter, currentSearchQuery);
                // 重新加载统计数据
                loadStatistics();
            } catch (error) {
                console.error('删除机器人失败:', error);
                showToast('删除机器人失败: ' + error.message, 'error');
            }
        }

        // 查看机器人详情
        async function viewRobotDetails(robotId) {
            try {
                const result = await apiRequest(`/api/robots/${robotId}`);
                const robot = result.data;
                
                // 这里可以打开详情模态框并显示机器人信息
                // 简化处理，暂时用提示框显示基本信息
                showToast(`查看 ${robot.name} (${robot.robot_id}) 的详情`);
                console.log('机器人详情:', robot);
                
                // 实际应用中可以在这里打开详情模态框
            } catch (error) {
                console.error('获取机器人详情失败:', error);
                showToast('获取机器人详情失败: ' + error.message, 'error');
            }
        }

        // 添加机器人模态框交互
        const addRobotModal = document.getElementById('add-robot-modal');
        const addRobotBtn = document.getElementById('add-robot-btn');
        const closeModalBtn = document.getElementById('close-modal-btn');
        const cancelAddBtn = document.getElementById('cancel-add-btn');
        const modalOverlay = document.getElementById('modal-overlay');
        const addRobotForm = document.getElementById('add-robot-form');
        const generateIdBtn = document.getElementById('generate-id-btn');
        const robotIdInput = document.getElementById('robot-id');

        // 显示模态框
        async function showModal() {
            addRobotModal.classList.remove('hidden');
            document.body.classList.add('overflow-hidden');
            // 重置表单
            addRobotForm.reset();
            // 生成机器人ID
            await generateRobotId();
        }

        // 隐藏模态框
        function hideModal() {
            addRobotModal.classList.add('hidden');
            document.body.classList.remove('overflow-hidden');
            // 重置表单验证状态
            addRobotForm.reset();
        }

        // 生成机器人ID（从API获取）
        async function generateRobotId() {
            try {
                const result = await apiRequest('/api/robots/generate-id');
                robotIdInput.value = result.data.robot_id;
            } catch (error) {
                console.error('生成机器人ID失败:', error);
                // 本地生成备用ID
                const date = new Date();
                const year = date.getFullYear();
                const randomNum = Math.floor(100 + Math.random() * 900);
                robotIdInput.value = `RB-${year}-${randomNum}`;
            }
        }

        // 提交添加机器人表单
        async function submitAddRobotForm(e) {
            e.preventDefault();
            
            // 获取表单数据
            const formData = {
                robot_id: document.getElementById('robot-id').value,
                name: document.getElementById('robot-name').value,
                type: document.querySelector('input[name="robot-type"]:checked')?.value,
                description: document.getElementById('robot-description').value,
                ip_address: document.getElementById('robot-ip').value,
                port: parseInt(document.getElementById('robot-port').value),
                protocol: document.getElementById('robot-protocol').value,
                battery_capacity: document.getElementById('battery-capacity').value ? parseInt(document.getElementById('battery-capacity').value) : null,
                max_load: document.getElementById('max-load').value ? parseFloat(document.getElementById('max-load').value) : null,
                move_speed: document.getElementById('move-speed').value ? parseFloat(document.getElementById('move-speed').value) : null,
                status: document.querySelector('input[name="initial-status"]:checked')?.value,
                create_default_task: true
            };
            
            try {
                // 提交表单
                await apiRequest('/api/robots', 'POST', formData);
                
                // 关闭模态框并显示成功提示
                hideModal();
                showToast('机器人添加成功！');
                
                // 重新加载机器人列表和统计数据
                loadRobots(1, currentStatusFilter, currentSearchQuery);
                loadStatistics();
                
            } catch (error) {
                console.error('添加机器人失败:', error);
                showToast('添加机器人失败: ' + error.message, 'error');
            }
        }

        // 状态筛选事件
        document.getElementById('status-filter').addEventListener('change', function() {
            const status = this.value;
            loadRobots(1, status, currentSearchQuery);
        });

        // 搜索事件
        document.getElementById('search-input').addEventListener('keyup', function(e) {
            // 按回车键搜索
            if (e.key === 'Enter') {
                const searchQuery = this.value.trim();
                loadRobots(1, currentStatusFilter, searchQuery);
            }
        });

        // 删除确认模态框事件
        document.getElementById('cancel-delete-btn').addEventListener('click', hideDeleteConfirmation);
        document.getElementById('confirm-delete-btn').addEventListener('click', confirmDeleteRobot);
        document.getElementById('delete-modal-overlay').addEventListener('click', hideDeleteConfirmation);

        // 添加机器人模态框事件
        addRobotBtn.addEventListener('click', showModal);
        closeModalBtn.addEventListener('click', hideModal);
        cancelAddBtn.addEventListener('click', hideModal);
        modalOverlay.addEventListener('click', hideModal);
        generateIdBtn.addEventListener('click', generateRobotId);
        addRobotForm.addEventListener('submit', submitAddRobotForm);

        // 点击模态框内容区域不关闭模态框
        const modalContent = addRobotModal.querySelector('.modal-enter');
        modalContent.addEventListener('click', function(e) {
            e.stopPropagation();
        });

        // 页面加载完成后初始化
        document.addEventListener('DOMContentLoaded', async () => {
            // 加载统计数据
            await loadStatistics();
            
            // 加载机器人列表
            await loadRobots();
            
            // 进度条动画
            setTimeout(() => {
                const progressBars = document.querySelectorAll('.progress-bar');
                progressBars.forEach(bar => {
                    const width = bar.style.width;
                    bar.style.width = '0';
                    setTimeout(() => {
                        bar.style.width = width;
                    }, 300);
                });
            }, 500);
        });
    </script>
</body>
</html>
    